package com.dayaokeji.rhythmschoolstudent.service;

import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.annotation.Nullable;

import com.dayaokeji.rhythmschoolstudent.BuildConfig;
import com.dayaokeji.rhythmschoolstudent.utils.AndroidUtils;
import com.dayaokeji.rhythmschoolstudent.utils.PrefUtils;
import com.dayaokeji.rhythmschoolstudent.utils.ServerCallback;
import com.dayaokeji.rhythmschoolstudent.utils.UserUtils;
import com.dayaokeji.server_api.ApiUtils;
import com.dayaokeji.server_api.ServerResponse;
import com.dayaokeji.server_api.api.SystemApi;
import com.dayaokeji.server_api.domain.Feedback;
import com.dayaokeji.server_api.domain.UserInfo;
import com.orhanobut.logger.Logger;

import java.text.SimpleDateFormat;
import java.util.Date;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Call;

/**
 * Created by Gorden on 2018/1/23.
 */

/**
 * 收集手机信息
 */
public class MobileInfoCollectService extends Service {

    private static final long SLEEP = 3 * 60 * 1000;
    private static final SystemApi systemApi = ApiUtils.getApi(SystemApi.class);
    private Call<ServerResponse<Void>> feedbackCall;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        whileSendAppInfoTask();
        return super.onStartCommand(intent, flags, startId);
    }


    private void whileSendAppInfoTask() {
        Observable.create(new ObservableOnSubscribe<Void>() {
            @Override
            public void subscribe(ObservableEmitter<Void> observableEmitter) throws Exception {
                while (!PrefUtils.isCollectMobileInfo()) {
                    try{
                        send();
                        SystemClock.sleep(SLEEP);
                    }catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }).subscribeOn(Schedulers.io()).subscribe();
    }

    /**
     * 发送反馈
     */
    private void send() {
        UserInfo userInfo = UserUtils.getUserInfo();
        if (userInfo != null) {
            final Feedback feedback = new Feedback();
            feedback.setUserId(userInfo.getId() != null? userInfo.getId():"");
            feedback.setContact(userInfo.getPhone() != null? userInfo.getPhone():"");
            feedback.setRetroaction(printSystemInfo());
            feedback.setVersion(AndroidUtils.getVersionName());
            feedback.setPhoneModels(Build.MODEL);
            feedback.setType(2);
            Logger.d(feedback.toString());
            feedbackCall = systemApi.feedback(feedback);
            serverCallback.setShowNetworkError(false);
            feedbackCall.enqueue(serverCallback);
        }
    }

    private ServerCallback serverCallback = new ServerCallback() {
        @Override
        public void onResponse(boolean success, ServerResponse response) {
            if (success) {
                PrefUtils.isCollectMobileInfo(true);
                Logger.d("上传手机信息成功");
            }
        }
    };

    @Override
    public void onDestroy() {
        if (feedbackCall != null) {
            feedbackCall.cancel();
        }
        super.onDestroy();

    }


    public static String printSystemInfo() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = dateFormat.format(date);
        StringBuilder sb = new StringBuilder();
        sb.append("_______  系统信息  ").append(time).append(" ______________");
        sb.append("\n设备ID             :").append(Build.ID);
        sb.append("\n手机厂商            :").append(Build.BRAND);
        sb.append("\n手机型号            :").append(Build.MODEL);
        sb.append("\n产品型号            :").append(Build.PRODUCT);
        sb.append("\n设备型号            :").append(Build.DEVICE);
        sb.append("\n系统版本            :").append("Android "+Build.VERSION.RELEASE);
        sb.append("\nApp版本            :").append("律动课堂 - v"+BuildConfig.VERSION_NAME);

        return sb.toString();
    }
}
